package com.ggbz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ggbz.entity.EvaluationCategories;
import com.ggbz.entity.dto.EvaluationCategoryRequest;
import com.ggbz.entity.dto.EvaluationCategoryUpdateRequest;
import com.ggbz.mapper.EvaluationCategoriesMapper;
import com.ggbz.service.EvaluationCategoriesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 评分大类表，存储评分的大类信息，例如竞赛、实践等，每个大类包含权重 服务实现类
 * </p>
 *
 * @author ggbz
 * @since 2025-03-08
 */
@Service
public class EvaluationCategoriesServiceImpl extends ServiceImpl<EvaluationCategoriesMapper, EvaluationCategories> implements EvaluationCategoriesService {
    @Autowired
    private EvaluationCategoriesMapper categoriesMapper;

    @Override
    public List<EvaluationCategories> getEvaluationCategories() {
        return categoriesMapper.selectList(null); // 查询全表数据
    }

    @Override
    @Transactional
    public void addEvaluationCategory(EvaluationCategoryRequest request) {
        // 检查分类名称是否重复
        QueryWrapper<EvaluationCategories> wrapper = new QueryWrapper<>();
        wrapper.eq("category_name", request.getCategoryName());
        int count = categoriesMapper.selectCount(wrapper);
        if (count > 0) {
            throw new RuntimeException("分类名称已存在");
        }

        // 2. 新增权重总和校验 ----------------------------
        List<EvaluationCategories> allCategories = categoriesMapper.selectList(null);

        // 使用BigDecimal避免浮点数精度问题
        BigDecimal totalWeight = allCategories.stream()
                .map(c -> BigDecimal.valueOf(c.getWeight()))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal newWeight = BigDecimal.valueOf(request.getWeight());
        if (totalWeight.add(newWeight).compareTo(BigDecimal.ONE) > 0) {
            throw new RuntimeException("权重总和不能超过1");
        }

        // 创建实体并保存
        EvaluationCategories category = new EvaluationCategories();
        category.setCategoryName(request.getCategoryName());
        category.setCategoryDescription(request.getCategoryDescription());
        category.setWeight(request.getWeight());

        categoriesMapper.insert(category);
    }

    @Override
    @Transactional
    public void updateEvaluationCategory(Long categoryId, EvaluationCategoryUpdateRequest request) {
        // 1. 检查分类是否存在
        EvaluationCategories existingCategory = categoriesMapper.selectById(categoryId);
        if (existingCategory == null) {
            throw new RuntimeException("分类不存在");
        }

        // 2. 检查分类名称是否重复（排除自身）
        if (!existingCategory.getCategoryName().equals(request.getCategoryName())) {
            QueryWrapper<EvaluationCategories> wrapper = new QueryWrapper<>();
            wrapper.eq("category_name", request.getCategoryName())
                    .ne("category_id", categoryId);
            if (categoriesMapper.selectCount(wrapper) > 0) {
                throw new RuntimeException("分类名称已存在");
            }
        }

        // 3. 权重总和校验（使用BigDecimal避免精度问题）
        BigDecimal originalWeight = BigDecimal.valueOf(existingCategory.getWeight());
        BigDecimal newWeight = BigDecimal.valueOf(request.getWeight());

        List<EvaluationCategories> allCategories = categoriesMapper.selectList(
                new QueryWrapper<EvaluationCategories>().ne("category_id", categoryId)
        );

        BigDecimal totalWeight = allCategories.stream()
                .map(c -> BigDecimal.valueOf(c.getWeight()))
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .add(newWeight);

        if (totalWeight.compareTo(BigDecimal.ONE) > 0) {
            throw new RuntimeException("权重总和不能超过1");
        }

        // 4. 执行更新
        UpdateWrapper<EvaluationCategories> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("category_id", categoryId)
                .set("category_name", request.getCategoryName())
                .set("category_description", request.getCategoryDescription())
                .set("weight", request.getWeight());

        categoriesMapper.update(null, updateWrapper);
    }

    @Override
    @Transactional
    public void deleteEvaluationCategory(Long categoryId) {
        // 1. 检查分类是否存在
        if (categoriesMapper.selectById(categoryId) == null) {
            throw new RuntimeException("分类不存在");
        }

        // 2. 直接执行删除
        int deleted = categoriesMapper.deleteById(categoryId);
        if (deleted == 0) {
            throw new RuntimeException("删除失败"); // 理论上不会进入此分支，除非并发删除
        }
    }
}
